package com.liupei.auth.controller;

import com.liupei.auth.entity.AuthToken;
import com.liupei.auth.service.AuthService;
import com.liupei.auth.vo.LoginUserVo;
import com.liupei.base.entity.Result;
import com.liupei.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

/**
 * @ClassNameLoginController
 * @Description
 * @Author liupei
 * @Emaile 3268727800@qq.com
 * @Date2021/3/16 11:00
 * @Version V1.0
 **/
@RestController
@RequestMapping(value = "/user")
public class LoginController {
    //客户端ID
    @Value("${auth.clientId}")
    private String clientId;

    //秘钥
    @Value("${auth.clientSecret}")
    private String clientSecret;

    //Cookie存储的域名
    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    //Cookie生命周期
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @Autowired
    private AuthService authService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Result login(@RequestBody @Validated LoginUserVo user) {
        //申请令牌
        AuthToken authToken =  authService.login(user.getUsername(),user.getPassword(),clientId,clientSecret);
        //用户身份令牌
        String access_token = authToken.getAccessToken();
        //将令牌存储到cookie
        //saveCookie(access_token);
        return Result.ok(authToken);
    }

    /***
     * 将令牌存储到cookie
     * @param token
     */
    private void saveCookie(String token){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response,cookieDomain,"/","Authorization",token,cookieMaxAge,false);
    }


}
